<?php
class Xigg_Admin_Plugin_Upgrade extends Sabai_Controller
{
    function _doExecute(&$context)
    {
        if (!$plugin_name = $context->request->getAsStr('plugin_name')) {
            $context->response->setError(_('No plugin specified'), Sabai_URL::get('/plugin'));
            return;
        }
        $plugin_manager =& $this->_locator->getService('PluginManager');
        if (!$plugin_data = $plugin_manager->getLocalPlugin($plugin_name, true)) {
            $context->response->setError(_('Invalid plugin'), Sabai_URL::get('/plugin'));
            return;
        }
        if (!$plugin = $plugin_manager->isPluginInstalled($plugin_name)) {
            $context->response->setError(_('Plugin not installed'), Sabai_URL::get('/plugin'));
            return;
        }
        if (!version_compare($plugin->get('version'), $plugin_data['version'], '<')) {
            $context->response->setError(_('Plugin is up to date'), Sabai_URL::get('/plugin'));
            return;
        }
        $plugin_params_form =& $this->_parent->getParamsForm($plugin_data, $plugin->getParams());
        if ($context->request->isPost()) {
            if ($plugin_params_form->validateValues($context->request->getAll())) {
                $params = array();
                foreach (array_keys($plugin_data['params']) as $param_name) {
                    $params[$param_name] = $plugin_params_form->getValueFor($param_name);
                    if ($plugin_data['params'][$param_name]['type'] == 'input_multi') {
                        $params[$param_name] = explode("\n", $params[$param_name]);
                    }
                }
                $plugin->setParams($params);
                $plugin->set('version', $plugin_data['version']);
                $plugin->set('active', $context->request->getAsBool('_active'));
                $model =& $this->_locator->getService('Model');
                if ($model->commit()) {
                    $context->response->setSuccess('Plugin upgraded successfully', Sabai_URL::get('/plugin'));
                    return;
                }
            }
        }
        $plugin_params_form->onView();
        $plugin_active = !$context->request->isPost() ? (bool)$plugin->get('active') : $context->request->getAsBool('_active');
        $context->response->setVars(array(
                                 'plugin_name'        => $plugin_name,
                                 'plugin_params_form' => &$plugin_params_form,
                                 'plugin_version'     => $plugin_data['version'],
                                 'plugin_summary'     => $plugin_data['summary'],
                                 'plugin_active'      => $plugin_active,
                                 'breadcrumb_current' => _('Upgrade Plugin')
                                    ));
    }
}